package com.tt.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.handlers.StrictFill;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

@Slf4j
@Component
public class MetaObjectHandlerConfig implements MetaObjectHandler {

    {
        log.info("MetaObjectHandlerConfig init...");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<Object> fieldVal) {
        //获取字段值，封装到Object对象中
        Object obj = fieldVal.get();
        //判断值是否为空
        if(Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }

}
